// router.js
import {
  RouterMount,
  createRouter
} from 'uni-simple-router'
import Vue from 'vue'
import store from '@/store'
import utils from '@/utils'
import ajax from '@/plugins/ajax'
import { APPID } from '@/env.js'

import pagesJson from '@/pages.json'

const { tabBar } = pagesJson

const tabBarList = tabBar.list.map(v => `/${v.pagePath}`)

const isTabbarPath = (path = '') => {
  return tabBarList.includes(path)
}

const router = createRouter({
  platform: process.env.VUE_APP_PLATFORM,
  routes: [...ROUTES]
})
// 全局路由前置守卫
router.beforeEach(async(to, from, next) => {
  if (utils.isWx()) {
    let locHref = window.location.href
    let redirectState = utils.getUrlParam('state')
    let code = utils.getUrlParam('code')
    if (code && redirectState && redirectState === utils.cache('wxRedirectState')) {
      utils.cache('wxRedirectState', null)
      let	fc = utils.getUrlParam('fc')
      let [authErr, authRes] = await utils.awaitTo(ajax.post)('app/wxAuth', { type: 0, code, fc })
      if (authErr) {
        let errNum = utils.cache('errNum') || 0
        if (errNum > 1) {
          alert(authErr.msg || authErr.data || '授权失败,请联系技术人员')
        } else {
          utils.cache('errNum', errNum + 1)
          let reUri = utils.delUrlParam(locHref.split('#')[0], ['code', 'state', 'reduri'])
          setTimeout(() => {
            window.location.href = reUri
          }, 500)
        }
        return next(false)
      } else {
        utils.storeToken(authRes.data.token)
        const redirectPath = utils.cache('redirectPath')
        if (redirectPath) {
          utils.cache('redirectPath', null)
          return next(redirectPath)
        }
      }
    }
    // else if (store.state.mountStatus === 0) {
    //   let mountStatus = isTabbarPath(to.path) ? 1 : 2
    //   store.commit('setState', { mountStatus })
    // } else if (store.state.mountStatus === 2 && isTabbarPath(to.path)) {
    //   store.commit('setState', { mountStatus: 1 })
    //   window.location.href = location.href.split('#')[0] + '#' + (to.path === '/pages/index/index' ? '/' : to.path)
    //   return next(false)
    // }
  }
  next()
})
var wxShareTimer = null
// 全局路由后置守卫
router.afterEach(async(to, from) => {
  wxShareTimer = setInterval(function() {
    if (store.state.config?.share_title) {
      clearInterval(wxShareTimer)
      utils.wxShare()
    }
  }, 1000)
})

export {
  router,
  RouterMount
}
